package nicolasb1.additifs;

import java.io.IOException;
import java.util.Locale;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Additifs extends ListActivity {
	private boolean isChangedState = false;
	private SimpleCursorAdapter notes;
	private Toast toast;
	SharedPreferences preferences;
	public int numberE = 0;
	public int numberGREEN = 0;
	public int numberORANGE = 0;
	public int numberRED = 0;
	// Langue
	public String langue = "auto";
	public boolean shouldChangeLocale = false;
	// Mode normal
	public String colorDefaut = "#84FF73";
	public String colorGREEN = "#84FF73";
	public String colorORANGE = "#FFDF5A";
	public String colorRED = "#FF797B";
	// Mode daltonien
	public String color2Defaut = "#accdff";
	public String color2GREEN = "#accdff";
	public String color2ORANGE = "#3773cd";
	public String color2RED = "#002357";	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        
        // Initialize preferences
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		langue = preferences.getString("lang", "auto");
		String locale = "";
		if(langue.compareTo("auto")==0)
		{
			locale = this.getResources().getConfiguration().locale.getDisplayName();
			locale = locale.substring(0, 2);
			locale = locale.toLowerCase();
			if(locale.compareTo("fr")==0)
			{
				langue = "fr";
			}
			else
			{
				langue = "en";
			}
		}
	    String languageToLoad = langue;
	    Locale locale2 = new Locale(languageToLoad);
	    Locale.setDefault(locale2);
	    Configuration config = new Configuration();
	    config.locale = locale2;
	    getBaseContext().getResources().updateConfiguration(config,
	    getBaseContext().getResources().getDisplayMetrics());
		ListView lv = getListView(); 
        lv.setFastScrollEnabled(true);
        
        // Show data
        refresh();
        
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int row, long arg3) {
           //String tmp1 = (String) arg0.
           //tmp[0] ist the Text of the first TextView displayed by the  clicked ListItem 

           onLongListItemClick(arg1,row,arg3); 
           return true;
        }});

        
    }
    protected void onLongListItemClick(View arg1, int row, long arg3) {
    	Cursor cursor = (Cursor) notes.getItem(row);
		String eid = cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEY_EID));
		String sitew = preferences.getString("longsite", "default");
		String requete;
		String eid2;
		if(langue.compareTo("fr")==0)
		{
			if(sitew.compareTo("weba")==0)
			{
				eid = eid.replace("(", "");
				eid = eid.replace(")", "");
				eid = eid.replace("i", "");
				eid = eid.replace("v", "");
				requete = "http://www.les-additifs-alimentaires.com/"+ eid + ".php";
			}
			else
			{
				if(sitew.compareTo("food")==0)
				{
					eid = eid.replace("(", "");
					eid = eid.replace(")", "");
					eid = eid.replace("i", "");
					eid = eid.replace("v", "");
					requete = "http://www.food-info.net/fr/e/"+eid.toLowerCase()+".htm";			
				}
				else
				{
					if(sitew.compareTo("ukfg")==0)
					{
						eid = eid.replace("(", "");
						eid = eid.replace(")", "");
						eid = eid.replace("i", "");
						eid = eid.replace("v", "");
						requete = "http://www.ukfoodguide.net/"+ eid.toLowerCase() + ".htm";			
					}
					else
					{
						requete = "http://fr.m.wikipedia.org/wiki/" + eid;
					}
				}
		    }
		}
		else
		{
			if(sitew.compareTo("weba")==0)
			{
				eid = eid.replace("(", "");
				eid = eid.replace(")", "");
				eid = eid.replace("i", "");
				eid = eid.replace("v", "");
				requete = "http://www.les-additifs-alimentaires.com/"+ eid + ".php";
			}
			else
			{
				if(sitew.compareTo("food")==0)
				{
					eid = eid.replace("(", "");
					eid = eid.replace(")", "");
					eid = eid.replace("i", "");
					eid = eid.replace("v", "");
					requete = "http://www.food-info.net/uk/e/"+eid.toLowerCase()+".htm";			
				}
				else
				{
					if(sitew.compareTo("ukfg")==0)
					{
						eid = eid.replace("(", "");
						eid = eid.replace(")", "");
						eid = eid.replace("i", "");
						eid = eid.replace("v", "");
						requete = "http://www.ukfoodguide.net/"+ eid.toLowerCase() + ".htm";			
					}
					else
					{
						requete = "http://en.m.wikipedia.org/wiki/" + eid;
					}
				}
		    }
		}
		Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(requete));
		startActivity(intent2);
    } 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
   		inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
	    String languageToLoad = langue;
	    Locale locale2 = new Locale(languageToLoad);
	    Locale.setDefault(locale2);
	    Configuration config = new Configuration();
	    config.locale = locale2;
	    getBaseContext().getResources().updateConfiguration(config,
	    getBaseContext().getResources().getDisplayMetrics());
        if (shouldChangeLocale) {
            menu.clear();
            MenuInflater inflater = getMenuInflater(); // -->onCreateMenu (Menu) 
            inflater.inflate(R.menu.menu, menu);  // /
            shouldChangeLocale=false;
        }

        return super.onMenuOpened(featureId, menu);
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    
	    if(isChangedState) {
	    	menu.findItem(R.id.bye).setVisible(true);
	    	menu.findItem(R.id.byname).setVisible(false);
	    	menu.findItem(R.id.prefs).setVisible(true);
	    	menu.findItem(R.id.legende).setVisible(true);
	    	menu.findItem(R.id.quitter).setVisible(true);
	    } else {
	    	menu.findItem(R.id.bye).setVisible(false);
	    	menu.findItem(R.id.byname).setVisible(true);
	    	menu.findItem(R.id.prefs).setVisible(true);
	    	menu.findItem(R.id.legende).setVisible(true);
	    	menu.findItem(R.id.quitter).setVisible(true);
	    }
	    return super.onPrepareOptionsMenu(menu);
    }

	// This method is called once the menu is selected
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// We have only one menu option
		case R.id.quitter:
			// Quit activity
			finish();
			break;
		case R.id.prefs:
			Intent i = new Intent(this, Preferences.class);
			startActivity(i);
			shouldChangeLocale = true;
			break;
		case R.id.legende:
			// Start activity
			Boolean dalto = preferences.getBoolean("dalto", false);
			Dialog dialog = new Dialog(Additifs.this);
	    	if(dalto)
	    	{
	    		dialog.setContentView(R.layout.legende_dalto);
	    	}
	    	else
	    	{
	    		dialog.setContentView(R.layout.legende);
	    	}
			if(langue.compareTo("fr")==0)
			{
				dialog.setTitle("Légende");
			}
			else
			{
				dialog.setTitle("Legend");
			}
			TextView legc1 = (TextView) dialog.findViewById(R.id.lgcolor1);
			TextView legb1 = (TextView) dialog.findViewById(R.id.legcolor1);
			TextView legc2 = (TextView) dialog.findViewById(R.id.lgcolor2);
			TextView legb2 = (TextView) dialog.findViewById(R.id.legcolor2);
			TextView legc3 = (TextView) dialog.findViewById(R.id.lgcolor3);
			TextView legb3 = (TextView) dialog.findViewById(R.id.legcolor3);
			TextView textTot = (TextView) dialog.findViewById(R.id.textTot);
			legc1.setText(Integer.toString(numberGREEN));
			legc2.setText(Integer.toString(numberORANGE));
			legc3.setText(Integer.toString(numberRED));
	        
	    	if(dalto)
	    	{
				legb1.setBackgroundColor(Color.parseColor(color2GREEN));
				legb2.setBackgroundColor(Color.parseColor(color2ORANGE));
				legb3.setBackgroundColor(Color.parseColor(color2RED));
	    	}
	    	else
	    	{
				legb1.setBackgroundColor(Color.parseColor(colorGREEN));
				legb2.setBackgroundColor(Color.parseColor(colorORANGE));
				legb3.setBackgroundColor(Color.parseColor(colorRED)); 		
	    	}
			textTot.setText("Nombre d'additifs : " + Integer.toString(numberE));
			dialog.show();
			break;
		case R.id.byname:
	        isChangedState = true;
	        refresh();
			break;
		case R.id.bye:
	        isChangedState = false;
	        refresh();
			break;
		}
		return true;
	}
	protected  void onListItemClick(ListView l, View v, int position, long id)
	{		 
		 super.onListItemClick(l, v, position, id);
		 Cursor cursor = (Cursor) notes.getItem(position);
		 String etyp = cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEY_COLOR));
		 String eid = cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEY_EID));
		 String etype = "Inoffensif";
         if(etyp.compareTo("GREEN") == 0)
         {
        	 etype = "Inoffensif";
         }
         if(etyp.compareTo("ORANGE") == 0)
         {
        	 etype = "À éviter";
         }
         if(etyp.compareTo("RED") == 0)
         {
        	 etype = "Dangereux";
         }
         if(toast == null)
         {
        	 toast = Toast.makeText(Additifs.this, eid+" : " +etype , Toast.LENGTH_SHORT);
         }
         else
         {
        	 toast.setText(eid+" : " +etype);
         }
		 toast.show();	
	}
	protected void onResume() {
	    super.onResume();
	    refresh();
	}
	private void refresh() {
		// TODO Auto-generated method stub
        DataBaseHelper myDbHelper = new DataBaseHelper(this);
        myDbHelper = new DataBaseHelper(this);

        try {
        	myDbHelper.createDataBase();
    	} catch (IOException ioe) {
			Toast.makeText(Additifs.this, "Unable to create database",
					Toast.LENGTH_LONG).show();
    		throw new Error("Unable to create database");
    	}

    	try {
    		myDbHelper.openDataBase();
    	}catch(SQLException sqle){
			Toast.makeText(Additifs.this, "Unable to open database",
					Toast.LENGTH_LONG).show();
    		throw sqle;
    	}
        //setListAdapter(new EfficientAdapter(this));
		langue = preferences.getString("lang", "auto");
		if(langue.compareTo("auto")==0)
		{
			String locale = this.getResources().getConfiguration().locale.getDisplayName();
			locale = locale.substring(0, 2);
			if(locale.compareTo("Fr")==0)
			{
				langue = "fr";
			}
			else
			{
				if(locale.compareTo("fr")==0)
				{
					langue = "fr";
				}
				else
				{
					langue = "en";
				}
			}
		}
	    String languageToLoad = langue;
	    Locale locale2 = new Locale(languageToLoad);
	    Locale.setDefault(locale2);
	    Configuration config = new Configuration();
	    config.locale = locale2;
	    getBaseContext().getResources().updateConfiguration(config,
	    getBaseContext().getResources().getDisplayMetrics());
        //setContentView(R.layout.list);
    	Cursor c;
    	if(isChangedState) {
    		if(langue.compareTo("fr")==0)
    		{
    			c = myDbHelper.fetchByName();
    		}
    		else
    		{
    			c = myDbHelper.fetchByName2();
    		}
    	}
    	else
    	{
    		if(langue.compareTo("fr")==0)
    		{
    			c = myDbHelper.fetchByEID();
    		}
    		else
    		{
    			c = myDbHelper.fetchByEID2();
    		}
    	}
        Cursor c1 = myDbHelper.fetchORANGE();
        Cursor c2 = myDbHelper.fetchRED();
        startManagingCursor(c);
        startManagingCursor(c1);
        startManagingCursor(c2);
        numberE = c.getCount();
        numberORANGE = c1.getCount();
        numberRED = c2.getCount();
        numberGREEN=numberE-(numberORANGE+numberRED);
        String[] from;
		if(langue.compareTo("fr")==0)
		{
	        from = new String[] { DataBaseHelper.KEY_EID, DataBaseHelper.KEY_NAME, DataBaseHelper.KEY_TYPE, DataBaseHelper.KEY_COLOR };
		}
		else
		{
	        from = new String[] { DataBaseHelper.KEY_EID, DataBaseHelper.KEY_NAME2, DataBaseHelper.KEY_TYPE2, DataBaseHelper.KEY_COLOR };
		}
        int[] to = { R.id.TextView01, R.id.TextView02, R.id.TextView03, R.id.img };

        // Now create an array adapter and set it to display using our row
        Boolean dalto = preferences.getBoolean("dalto", false);
    	if(dalto)
    	{
            notes = new SimpleCursorAdapter(this, R.layout.main_dalto, c, from, to);
    	}
    	else
    	{
            notes = new SimpleCursorAdapter(this, R.layout.main, c, from, to);
    	}
        notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {      
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            	boolean retval = false;
            	
            	int nIndex = cursor.getColumnIndexOrThrow(DataBaseHelper.KEY_COLOR);

                if ( columnIndex == nIndex) 
                {	
                	TextView tv2 = (TextView) view;
                    String status = cursor.getString(nIndex);
                    Boolean dalto = preferences.getBoolean("dalto", false);
                	if(dalto)
                	{
                		tv2.setBackgroundColor(Color.parseColor(color2Defaut));
	                    if(status.compareTo("GREEN") == 0)
	                    {
                    		tv2.setBackgroundColor(Color.parseColor(color2GREEN));
                    		retval = true;
	                    }
	                    if(status.compareTo("ORANGE") == 0)
	                    {            	
	                    	tv2.setBackgroundColor(Color.parseColor(color2ORANGE));
	                    	retval = true;
	                    }
	                    if(status.compareTo("RED") == 0)
	                    {
	                    	tv2.setBackgroundColor(Color.parseColor(color2RED));
	                    	retval = true;
	                    }
                	}
                	else
                	{
                		tv2.setBackgroundColor(Color.parseColor(colorDefaut));
	                    if(status.compareTo("GREEN") == 0)
	                    {
                    		tv2.setBackgroundColor(Color.parseColor(colorGREEN));
                    		retval = true;
	                    }
	                    if(status.compareTo("ORANGE") == 0)
	                    {            	
	                    	tv2.setBackgroundColor(Color.parseColor(colorORANGE));
	                    	retval = true;
	                    }
	                    if(status.compareTo("RED") == 0)
	                    {
	                    	tv2.setBackgroundColor(Color.parseColor(colorRED));
	                    	retval = true;
	                    }
                    }
                    
                }
                return retval;
            }
        });
        setListAdapter(notes);
        myDbHelper.close();
	}
	
	
}
